// JavaScript Document new

var gSelectedResults = [];
var gCurrentResults = [];
var eids = [];


// Create our "tiny" marker icon
var gYellowIcon = new google.maps.MarkerImage(
    "http://labs.google.com/ridefinder/images/mm_20_yellow.png",
    new google.maps.Size(12, 20),
    new google.maps.Point(0, 0),
    new google.maps.Point(6, 20));
var gRedIcon = new google.maps.MarkerImage(
    "http://labs.google.com/ridefinder/images/mm_20_red.png",
    new google.maps.Size(12, 20),
    new google.maps.Point(0, 0),
    new google.maps.Point(6, 20));
var gSmallShadow = new google.maps.MarkerImage(
    "http://labs.google.com/ridefinder/images/mm_20_shadow.png",
    new google.maps.Size(22, 20),
    new google.maps.Point(0, 0),
    new google.maps.Point(6, 20));

var bounds;
 
/////////////////////////////////////////////////////////////////////
/////////// funzioni di ricerca su gmap /////////////////////////////
/////////////////////////////////////////////////////////////////////
 
function unselectMarkers() {
    for (var i = 0; i < gCurrentResults.length; i++) {
        gCurrentResults[i].unselect();
    }
    target = false;
}

// ricerca centrata sul marker dell'utente
function doSearch() {
    $("#loader").fadeIn();
    bounds = gMap.getBounds();
    var NElat = bounds.getNorthEast().lat();
    var NElng = bounds.getNorthEast().lng();
    var SWlat = bounds.getSouthWest().lat();
    var SWlng = bounds.getSouthWest().lng();
    var data_from = document.getElementById("data-from").value;
    var data_to = document.getElementById("data-to").value;
    //    var city_form = document.getElementById("city-form").value;
    $.post(baseURL, 
    { 
        //     max_lat: NElat,
        //     max_lng: NElng,
        //     min_lat: SWlat,
        //     min_lng: SWlng,
        from:    data_from,
        to:      data_to
    //        city:    city_form 
    },
    function(data){
        OnLocalSearch(data);
        $("#loader").fadeOut();
    }, "text").error("Error in servlet response.");
}
 
 
// Called when Local Search results are returned, we clear the old
// results and load the new ones.
function OnLocalSearch(resultsFinal) {
    var arrayResults = resultsFinal.split(";");
    
    var sponsored = jQuery.parseJSON(arrayResults[0]);
    var results = jQuery.parseJSON(arrayResults[1]);
    
    var sponsorised = document.getElementById("sponsorised");
    var searchWell = document.getElementById("searchwell");

    // Clear the map and the old search well
    sponsorised.innerHTML = "";
    searchWell.innerHTML = "";
    for (var i = 0; i < gCurrentResults.length; i++) {
        gCurrentResults[i].marker().setMap(null);
    }
    
    // Close the infowindow
    gInfoWindow.close();
	
    gCurrentResults = [];
    eids = [];
    
    for (var k = 0; k < sponsored.length; k++) {
        var spo = new LocalResult(sponsored[k], true);
        if(spo.result) // se l'evento ha un indirizzo
            gCurrentResults.push(spo);
    }
    
    
    for (var j = 0; j < results.length; j++) {
        var res = new LocalResult(results[j], false);
        if(res.result) // se l'evento ha un indirizzo
            gCurrentResults.push(res);
    }
}
 
// Cancel the form submission, executing an AJAX Search API search.
function CaptureForm(searchForm) {
    gLocalSearch.execute(searchForm.input.value);
    return false;
}
 
 
// A class representing a single Local Search result returned by the
// Google AJAX Search API.
function LocalResult(result, type) {
    var me = this;
    me.result_ = result;
    me.resultNode_ = me.node();
    me.marker_ = me.marker();
    me.result = true;
    
    // se non sono riuscito a georeferenziare
    if(!me.marker_)
        me.result = false;
    // evento duplicato
    if(me.result && jQuery.inArray(me.result_.eid, eids) > -1){
        me.result = false;
        me.marker_.setVisible(false);
    }
        
    // evento fuori range
    if(me.result && !bounds.contains(me.location)){
        me.result = false;
        me.marker_.setVisible(false);
    }
    // se c'è stato un errore, esce
    if(!me.result) return;

    google.maps.event.addDomListener(me.resultNode_, 'mouseover', function() {
        // Highlight the marker and result icon when the result is
        // mouseovered.  Do not remove any other highlighting at this time.
        me.highlight(true);
    });
    google.maps.event.addDomListener(me.resultNode_, 'mouseout', function() {
        // Remove highlighting unless this marker is selected (the info
        // window is open).
        if (!me.selected_) me.highlight(false);
    });
    google.maps.event.addDomListener(me.resultNode_, 'click', function() {
        me.select();
    });
    if(me.resultNode_ && type)
        document.getElementById("sponsorised").appendChild(me.resultNode_);
    if(me.resultNode_ && !type){
        document.getElementById("searchwell").appendChild(me.resultNode_);
        eids.push(me.result_.eid);
    }
    
}

LocalResult.prototype.node = function() {
    if (this.resultNode_) return this.resultNode_;
    return this.html();
};
 
// Returns the GMap marker for this result, creating it with the given
// icon if it has not already been created.
LocalResult.prototype.marker = function() {
    var me = this;
    if (me.marker_)return me.marker_;
    // devo valutare l'evento
    // se georeferenziato creo un oggetto locatio
    // altrimenti devo georeferenziarlo sulla città dell'utente
    var Venue = me.result_.venue;
    
    if(Venue.latitude){
        var lat = Venue.latitude;
        var lng = Venue.longitude;
        var GeoRef = new google.maps.LatLng(lat, lng);
        this.location = GeoRef;
        var marker = me.marker_ = new google.maps.Marker({
            position: GeoRef,
            icon: gYellowIcon, 
            shadow: gSmallShadow, 
            map: gMap
        });
        google.maps.event.addListener(marker, "click", function() {
            this.select();
        });
        return marker;
    } 
    return false;
};
 
// Unselect any selected markers and then highlight this result and
// display the info window on it.
LocalResult.prototype.select = function() {
    unselectMarkers();
    this.selected_ = true;
    this.highlight(true);
    gInfoWindow.setContent(this.html(true));
    gInfoWindow.open(gMap, this.marker());
    target = this.location;
	
    var arrivo = document.querySelector('#arrivo');
    var indirizzo_geo = codeLatLng(target);	
    if(indirizzo_geo) arrivo.value = indirizzo_geo;
};
 
LocalResult.prototype.isSelected = function() {
    return this.selected_;
};
 
// Remove any highlighting on this result.
LocalResult.prototype.unselect = function() {
    this.selected_ = false;
    this.highlight(false);
};
 
// Returns the HTML we display for a result before it has been "saved"
LocalResult.prototype.html = function() {
    var me = this.result_;
     
    var container = document.createElement("div");
    container.className = "unselected";
    
    var title = document.createElement("h4");
    title.className = "event-title";
    var textNode = document.createTextNode(String(me.name));
    title.appendChild(textNode);
    container.appendChild(title);
    
    var bdy = document.createElement("div");
    bdy.className = "event-body";
    container.appendChild(bdy);
    
    if(me.description){
        var desc = document.createElement("div");
        desc.className = "desc";
        var description = document.createTextNode(String(me.description));
        desc.appendChild(description);
        bdy.appendChild(desc);
    }
    
    if(me.location){
        var loc = document.createElement("div");
        loc.className = "loc";
        var loc2 = document.createTextNode(String(me.location));
        loc.appendChild(loc2);
        bdy.appendChild(loc);
    }
    
    return container;
}
 
LocalResult.prototype.highlight = function(highlight) {
    this.marker().setOptions({
        icon: highlight ? gRedIcon : gYellowIcon
    });
    this.node().className = "unselected" + (highlight ? " red" : "");
}

